<?php

namespace App\Http\Controllers;

use App\Models\YzPayment;
use App\Models\UserDcoinsLog;
use Auth;
use DB;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Pay\Youzan;

class PayController extends Controller
{
    public function __construct()
    {
         $this->middleware('auth')->except(['responseMsg']);
    }
    public function responseMsg()
    {
        $postMsg = file_get_contents("php://input");
        Log::useFiles(storage_path() .'/logs/youzan.log');
        Log::info('有赞-用户支付', ['postMsg' => $postMsg]);
        $data = json_decode($postMsg, true);
        /**
         * 判断消息是否合法，若合法则返回成功标识
         */
        $client_id = config('youzan.client_id');
        $client_secret = config('youzan.client_secret');
        $msg = $data['msg'];
        $sign_string = $client_id."".$msg."".$client_secret;
        $sign = md5($sign_string);
        if($sign != $data['sign'])
        {
            exit();
        }
        else
        {
            $result = array("code" => 0,"msg" => "success") ;
            var_dump($result);
        }
        /**
         * msg内容经过 urlencode 编码，需进行解码
         */
        //$msg = json_decode(urldecode($msg),true);
        $kdt_id = config('youzan.kdt_id');
        if($data['type'] == 'trade_TradePaid' && $data['kdt_id'] == $kdt_id && Auth::check())
        {
            $trade = Youzan::getOneTradeByTid($data['id']);
            $payment = YzPayment::where('qr_id', $trade['qr_info']['qr_id'])->first();

            if ($payment && $payment->status !== YzPayment::TRADE_SUCCESS)
            {
                try
                {
                    //事务处理
                    DB::transaction(function () use($payment) {

                        $payment->status = YzPayment::TRADE_SUCCESS;
                        $payment->save();
                        if($payment->type == YzPayment::TYPE_DCOINS)
                        {
                            //增加用户D币
                            $dcoin_statistic = UserDcoinsLog::dcoinStatistic($payment->user_id);
                            $dcoin_log = UserDcoinsLog::getDcoinLogByPaymentId($payment->id);
                            if(empty($dcoin_log))
                            {
                                $userDcoinsLog = new UserDcoinsLog();
                                $userDcoinsLog->user_id = $payment->user_id;
                                $userDcoinsLog->type = 1;//增加
                                $userDcoinsLog->dcoins = $payment->qr_price * 10;
                                $userDcoinsLog->remain_dcoins = $dcoin_statistic['remain_dcoins'] + $userDcoinsLog->dcoins;
                                $userDcoinsLog->reason_type = UserDcoinsLog::REASON_TYPE_SIGN;//赞助
                                $userDcoinsLog->yz_payment_id = $payment->id;
                                $userDcoinsLog->save();
                            }

                        }
                        elseif($payment->type == YzPayment::TYPE_VIP)
                        {
                            /** @var VipBaseInfo $vipBaseInfo */
                            $vipBaseInfo = VipBaseInfo::find($payment->vip_id);

                            $expireDate = $vipBaseInfo->getExpireDate(Carbon::now());

                            $userVipInfo = [
                                'vip_base_info_id' => $payment->vip_id,
                                'vip_name' => $vipBaseInfo->name,
                                'privilege_str' => $vipBaseInfo->privilege_str,
                                'homework_help_discount' => $vipBaseInfo->homework_help_discount,
                                'algorithm_sources_discount' => $vipBaseInfo->algorithm_sources_discount,
                                'resource_discount' => $vipBaseInfo->resource_discount,
                                'is_exempt_ads' => $vipBaseInfo->is_exempt_ads,
                                'start_date' => date('Y-m-d H:i:s', time()),
                                'expire_date' => $expireDate,
                            ];

                            $points = UserPointsLog::getLatestUPLog($payment->user_id);
                            $Dconin = UserDcoinsLog::getLatestUDcoinLog($payment->user_id);
                            $userVipFreeOpeCountLog = UserVipFreeOpeCountLog::getLatestLog($payment->user_id);
                            $newUserVipFreeOpeCountLog = new UserVipFreeOpeCountLog();
                            $userVipOpeLog = new UserVipOpeLog();

                            $userVipOpeLog->user_id = $payment->user_id;
                            $userVipOpeLog->vip_id = $vipBaseInfo->id;
                            $userVipOpeLog->vip_info = $vipBaseInfo;
                            $userVipOpeLog->user_vip_info = $userVipInfo;
                            $userVipOpeLog->remark = '开通vip';
                            $userVipOpeLog->yz_payment_id = $payment->id;

                            $newUserVipFreeOpeCountLog->user_id = $payment->user_id;
                            $newUserVipFreeOpeCountLog->ope = UserVipFreeOpeCountLog::ADD_OPE;
                            $newUserVipFreeOpeCountLog->free_home_help_ope_count = $vipBaseInfo->free_homework_help_count;
                            $newUserVipFreeOpeCountLog->free_home_help_remain_count = ($userVipFreeOpeCountLog->free_home_help_remain_count ?? 0) + $vipBaseInfo->free_homework_help_count;
                            $newUserVipFreeOpeCountLog->free_resource_ope_count = $vipBaseInfo->free_resource_point_count;
                            $newUserVipFreeOpeCountLog->free_resource_remain_count = ($userVipFreeOpeCountLog->free_resource_remain_count ?? 0) + $vipBaseInfo->free_resource_point_count;
                            $newUserVipFreeOpeCountLog->free_algorithm_sources_ope_count = $vipBaseInfo->free_algorithm_sources_count;
                            $newUserVipFreeOpeCountLog->free_algorithm_sources_remain_count = ($userVipFreeOpeCountLog->free_algorithm_sources_remain_count ?? 0) + $vipBaseInfo->free_algorithm_sources_count;
                            $newUserVipFreeOpeCountLog->remark = '开通vip：' . $vipBaseInfo->privilege_str;
                            $newUserVipFreeOpeCountLog->yz_payment_id = $payment->id;

                            DB::transaction(function () use ($payment, $points, $Dconin, $userVipInfo, $newUserVipFreeOpeCountLog, $userVipOpeLog, $vipBaseInfo) {
                                $user = User::findorFail($payment->user_id);
                                $user->vipInfo()->updateOrCreate(['user_id' => $payment->user_id], $userVipInfo);
                                $newUserVipFreeOpeCountLog->save();
                                $userVipOpeLog->save();

                                if ($vipBaseInfo->resource_point > 0) {
                                    $newPoints = new UserPointsLog();
                                    $newPoints->user_id = $user->id;
                                    $newPoints->type = 1; //增加
                                    $newPoints->points = $vipBaseInfo->resource_point;
                                    $newPoints->remain_points = ($points->remain_points ?? 0) + $vipBaseInfo->resource_point;
                                    $newPoints->reason_type = UserPointsLog::REASON_TYPE_VIP_ADD;
                                    $newPoints->yz_payment_id = $payment->id;
                                    $newPoints->remark = '开通vip：' . $vipBaseInfo->privilege_str;
                                    $newPoints->save();
                                }

                                if ($vipBaseInfo->algorithm_sources_icon > 0) {
                                    $newDconin = new UserDcoinsLog();
                                    $newDconin->user_id = $user->id;
                                    $newDconin->type = 1; //增加
                                    $newDconin->dcoins = $vipBaseInfo->algorithm_sources_icon;
                                    $newDconin->remain_dcoins = ($Dconin->remain_dcoins ?? 0) + $vipBaseInfo->algorithm_sources_icon;
                                    $newDconin->reason_type = UserDcoinsLog::REASON_TYPE_VIP_ADD;
                                    $newDconin->yz_payment_id = $payment->id;
                                    $newDconin->remark = '开通vip：' . $vipBaseInfo->privilege_str;
                                    $newDconin->save();
                                }
                            });
                        }

                    });
                }
                catch (\Illuminate\Database\QueryException $ex)
                {

                }
            }
        }
    }


    public function getTradeList()
    {
        return Youzan::getTradeList();
    }

    public function getOneTrade()
    {
        //var_dump(Youzan::getOneTradeByTid('E20181112203526079100001'));
    }

    /*
     * 查询订单状态
     */
    public function paymentStatus(Request $request)
    {
        $payment_id = $request->input('payment_id');
        $payment = YzPayment::where('id', $payment_id)->first();

        $parames = ['qr_id'     => $payment->qr_id,
                    'status'    => 'TRADE_RECEIVED'
                    ];

        $trade = Youzan::getSpecifiedTrade($parames);
        if($trade['total_results'] > 0 && $payment->status !== YzPayment::TRADE_SUCCESS)
        {
            $payment->qr_price = $trade['qr_trades'][0]['real_price'];
            try
            {
                DB::transaction(function () use($payment) {
                    $payment->status = YzPayment::TRADE_SUCCESS;
                    $payment->save();
                    //增加用户D币
                    $dcoin_statistic = UserDcoinsLog::dcoinStatistic($payment->user_id);
                    $dcoin_log = UserDcoinsLog::getDcoinLogByPaymentId($payment->id);
                    if(empty($dcoin_log))
                    {
                        $userDcoinsLog = new UserDcoinsLog();
                        $userDcoinsLog->user_id = $payment->user_id;
                        $userDcoinsLog->type = 1;//增加
                        $userDcoinsLog->dcoins = $payment->qr_price * 10;
                        $userDcoinsLog->remain_dcoins = $dcoin_statistic['remain_dcoins'] + $userDcoinsLog->dcoins;
                        $userDcoinsLog->reason_type = UserDcoinsLog::REASON_TYPE_SIGN;//赞助
                        $userDcoinsLog->yz_payment_id = $payment->id;
                        $userDcoinsLog->save();
                    }
                });
                $payment['msg'] = '赞助成功';
            }
            catch (\Illuminate\Database\QueryException $ex)
            {
                $payment['msg'] = '赞助失败';
            }
        }
        return response()->json($payment);
    }

}